package com.wsl.controller;

import com.wsl.Entity.Person;
import com.wsl.repository.PersonRepository;
import com.wsl.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author:WangShuliang
 * @Description:
 * @Date:Created in 22:36 2017/11/28
 * @Modified by:
 */
@RestController
public class DataController {
    @Autowired//Spring Data JPA已经自动注册Bean 所以可以自动注入
    PersonRepository personRepository;
    @Autowired
    DemoService demoService;
    @RequestMapping("/q1")
    public List<Person> q1(String address){
        List<Person> people = personRepository.findByAddress(address);
        return people;
    }
    @RequestMapping("/save")
    public Person save(String name,String address,Integer age){
        Person p = personRepository.save(new Person(null,name,age,address));
        return p;
    }
    @RequestMapping("/q2")
    public Person q2(String name,String address){
        Person person = personRepository.findByNameAndAddress(name,address);
        return person;
    }
    @RequestMapping("/q3")
    public Person q3(String name,String address){
        Person person= personRepository.withNameAndAddressQuery(name, address);
        return person;
    }
    @RequestMapping("/q4")
    public Person q4(String name,String address){
        Person person = personRepository.withNameAndAddressQuery(name,address);
        return person;
    }

    /**
     * 测试排序
     * @return
     */
    @RequestMapping("/sort")
    public List<Person> sort(){
        List<Person> people = personRepository.findAll(new Sort(Sort.Direction.ASC,"age"));
        return people;
    }
    @RequestMapping("/page")
    public Page<Person> page(){
        Page<Person> pagePeople = personRepository.findAll(new PageRequest(1,1));
        return  pagePeople;
    }
    @RequestMapping("/rollback")
    public Person rollback(Person person){
        return demoService.savePersonWithRollBack(person);
    };

    @RequestMapping("/norollback")
    public Person noRollBack(Person person){
        return demoService.savePersonWithoutRollBack(person);
    }

    @RequestMapping("/sqlRollback")
    public Person sqlRollback(Person person) {
        return demoService.sqlRollback(person);
    }
}
